#include "mythread.h"

#include "GY_8507_Func.h"
#include "log_Gen.h"


Mythread::Mythread(QObject *parent) : QObject(parent)
{


}



void Mythread::on_Rev(DEVICE_HANDLE Channel)
{
    qDebug()<<"on_Rev Staring";
    ZCAN_Receive_Data can_data[300];



    UINT len;
    UINT RecLen;
    UINT sum = 0;
    while(true)
    {
        if(g_DevType_ZLG1_GY2 == 1)
        {
            len = ZCAN_GetReceiveNum(Channel, TYPE_CAN);
            if (len!=0 )
            {
                RecLen = ZCAN_Receive(Channel, can_data, len, 50);
                sum = sum + RecLen;
                emit CAN_DAT(can_data,RecLen); //数据发送到主线程显示
            }
            else
            {  if(sum!=0)
                {
                  // qDebug()<<"RECV NUM"<<sum;
                   sum = 0;
                }
            }
        }
        else  if(g_DevType_ZLG1_GY2 == 2)
        {
            RecLen = GY8507CAN_GetReceive(can_data);
            if(RecLen > 0)
            {
               emit CAN_DAT(can_data,RecLen); //数据发送到主线程显示
            }
        }
        //避免无数据时死循环,会占用大量的CPU
        QThread::usleep(500);
    }
}



int32_t Mythread:: GY8507CAN_GetReceive( ZCAN_Receive_Data *can_data)
{
    uint16_t Value = 0;

    uint32_t   CAN_ID = 0;

    memset(candatabuf,0,sizeof(candatabuf));

    Value = VCI_Receive(DEV_USBCAN,0,0,candatabuf);
    if(Value > 0)
    {
        for(int i = 0; i<Value; i++)
        {
            memcpy(can_data[i].frame.data,candatabuf[i].Data,8);
            CAN_ID = candatabuf[i].ID;

            uint32_t  can_id_byte1 = ( CAN_ID & 0x000000FF ) << 24;
            uint32_t  can_id_byte2 = ( CAN_ID & (uint32_t)0x0000FF00 ) << 8;
            uint32_t  can_id_byte3 = ( CAN_ID & (uint32_t)0x00FF0000 ) >> 8;
            uint32_t  can_id_byte4 = ( CAN_ID & (uint32_t)0xFF000000 ) >> 24;

            uint32_t can_id_last = (can_id_byte1 + can_id_byte2 + can_id_byte3 + can_id_byte4) >> 3;

            can_data[i].frame.can_id = can_id_last + 0x80000000;
            can_data[i].frame.can_dlc = candatabuf[i].DataLen;

        }
    }
    return Value;
}
